import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import UIAbility from '@ohos.app.ability.UIAbility';
import Want from '@ohos.app.ability.Want';
import window from '@ohos.window';
import Log from '../utils/Logger';

const TAG = 'EntryAbility_Ble'

export default class EntryAbility extends UIAbility {

  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    this.startService()
    this.context.terminateSelf()
  }

  onDestroy(): void {
  }

  async onWindowStageCreate(windowStage: window.WindowStage) {
    // Main window is created, set main page for this ability
    Log.info(TAG, 'Ability onWindowStageCreate');
  }

  onWindowStageDestroy(): void {
    // Main window is destroyed, release UI related resources
    Log.info(TAG, 'Ability onWindowStageDestroy');
  }

  onForeground(): void {
    // Ability has brought to foreground
    Log.info(TAG, 'Ability onForeground');
  }

  onBackground(): void {
    // Ability has back to background
    Log.info(TAG, 'Ability onBackground');
  }

  async startService(): Promise<boolean> {
    try {
      await this.context.startServiceExtensionAbility({
        bundleName: 'com.ohos.bleclient',
        abilityName: 'ServiceAbility'
      })
      Log.info(TAG, 'startService success');
      return true
    } catch (err) {
      Log.error(TAG, 'startService failed');
      return false
    }
  }

  async stopService(): Promise<boolean> {
    try {
      await this.context.stopServiceExtensionAbility({
        bundleName: 'com.ohos.bleclient',
        abilityName: 'ServiceAbility'
      })
      Log.info(TAG, 'startService success');
      return true
    } catch (err) {
      Log.error(TAG, 'startService failed');
      return false
    }
  }
}
